"""
主程序入口
"""

import tkinter as tk
from tkinter import messagebox  # 添加messagebox导入
from gui import PromptAssistantGUI
from data_manager import DataManager
from hotkey_manager import HotkeyManager
from config import GLOBAL_HOTKEY
import os
import sys
import traceback
import logging
from datetime import datetime
import json
import pyperclip
import keyboard
import asyncio
from configs.set_configs import verify_prompt_dir
from history_module.history_list import HistoryWindow
import time

# 导入新的编辑管理器模块
from edit_manager import EditManager

# 尝试导入win32clipboard
try:
    import win32clipboard
    WIN32CLIP_AVAILABLE = True
except ImportError:
    WIN32CLIP_AVAILABLE = False

# 配置日志
def setup_logging():
    """设置日志"""
    if not os.path.exists('logs'):
        os.makedirs('logs')
    
    log_file = os.path.join('logs', f'error_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log')
    logging.basicConfig(
        filename=log_file,
        level=logging.ERROR,
        format='%(asctime)s - %(levelname)s - %(message)s'
    )

def perform_startup_checks():
    """执行启动自检"""
    try:
        # 检查data目录
        if not os.path.exists('data'):
            os.makedirs('data')
    except Exception as e:
        logging.error(f"启动自检失败: {str(e)}")
        messagebox.showerror("错误", f"启动自检失败: {str(e)}")

def maximize_window(root):
    """跨平台窗口最大化"""
    try:
        # Windows平台
        root.state('zoomed')
    except:
        try:
            # Linux/Unix平台
            root.attributes('-zoomed', True)
        except:
            # 如果以上方法都失败，使用屏幕尺寸
            screen_width = root.winfo_screenwidth()
            screen_height = root.winfo_screenheight()
            root.geometry(f"{screen_width}x{screen_height}+0+0")

async def async_main():
    try:
        # 设置日志
        setup_logging()
        
        # 执行启动自检
        perform_startup_checks()
        
        # 验证提示词目录 - 移到数据加载之前
        verify_prompt_dir()
        
        root = tk.Tk()
        root.title("提示词小助手")
        
        # 使用跨平台的窗口最大化方法
        maximize_window(root)
        
        # 设置最小窗口大小
        root.minsize(800, 600)
        
        # 初始化数据管理器
        data_manager = DataManager()
        hotkey_manager = HotkeyManager()
        
        # 创建GUI
        app = PromptAssistantGUI(root, data_manager, hotkey_manager)
        
        # 将 app 实例存储到 root 中，以便其他窗口可以访问
        root.app = app
        
        # 创建编辑管理器实例
        # edit_manager = EditManager(root, data_manager)
        
        # 添加"编辑界面"按钮
        # edit_button = tk.Button(root, text="编辑界面", command=edit_manager.open_edit_window)
        # edit_button.pack(side=tk.TOP, padx=10, pady=10)
        
        # 绑定右键双击事件到主窗口的空白区域
        def open_history_window(event):
            # 获取点击的控件
            clicked_widget = event.widget
            # 检查点击的是否是主窗口、分组列表或提示词列表
            if clicked_widget in [root, app.group_list, app.file_list]:
                HistoryWindow(root)
        
        # 绑定右键双击事件到主窗口和列表框
        root.bind("<Double-Button-3>", open_history_window)
        app.group_list.bind("<Double-Button-3>", open_history_window)
        app.file_list.bind("<Double-Button-3>", open_history_window)
        
        # 加载数据
        data_all = data_manager.load_all_json_data()
        
        # 注册热键
        hotkey_manager.register_hotkeys(data_all)
        hotkey_manager.register_global_hotkey(
            GLOBAL_HOTKEY, 
            lambda: app.send_cache_prompt_toclipboard()
        )
        hotkey_manager.start_listener()
        
        # 加载高频快捷键配置，并通过hotkey_manager统一注册
        # 自动注册高频快捷键（无需打开面板）
        high_freq_config_path = os.path.join('configs_all', 'hotkey_configs.json')
        if os.path.exists(high_freq_config_path):
            cleaned = False
            cleaned_count = 0
            try:
                with open(high_freq_config_path, 'r', encoding='utf-8') as f:
                    high_freq_hotkeys = json.load(f)
                valid_hotkeys = {}
                used_hotkeys = set()
                for index_str, config in high_freq_hotkeys.items():
                    hotkey = config.get('hotkey', '')
                    filename = config.get('filename', '')
                    file_path = data_manager.get_data_path(filename)
                    # 检查基本有效性
                    if not hotkey or not filename or not os.path.exists(file_path):
                        cleaned = True
                        cleaned_count += 1
                        continue
                    # 检查快捷键唯一性
                    if hotkey in used_hotkeys:
                        cleaned = True
                        cleaned_count += 1
                        continue
                    used_hotkeys.add(hotkey)
                    valid_hotkeys[index_str] = {'hotkey': hotkey, 'filename': filename}
                # 如果有清理，写回文件并弹窗提示
                if cleaned:
                    with open(high_freq_config_path, 'w', encoding='utf-8') as f:
                        json.dump(valid_hotkeys, f, ensure_ascii=False, indent=4)
                    messagebox.showwarning("高频快捷键配置已清理", f"检测到高频快捷键配置存在无效、重复或丢失文件的项，已自动清理 {cleaned_count} 条。", parent=root)
                # 用清理后的数据注册
                for index_str, config in valid_hotkeys.items():
                    hotkey = config.get('hotkey', '')
                    filename = config.get('filename', '')
                    file_path = data_manager.get_data_path(filename)
                    def create_callback(fname):
                        def callback():
                            try:
                                with open(data_manager.get_data_path(fname), 'r', encoding='utf-8') as f2:
                                    data = json.load(f2)
                                    content = data.get('content', '')
                                    # 增强版：多次清空写入并校验，检测是否被截图工具占用
                                    success = False
                                    last_error = None
                                    if WIN32CLIP_AVAILABLE:
                                        for _ in range(5):
                                            try:
                                                win32clipboard.OpenClipboard()
                                                win32clipboard.EmptyClipboard()
                                                win32clipboard.SetClipboardText(content)
                                                win32clipboard.CloseClipboard()
                                                time.sleep(0.2)  # 稍作延迟，防止截图工具抢占
                                                # 校验写入内容
                                                win32clipboard.OpenClipboard()
                                                try:
                                                    clipdata = win32clipboard.GetClipboardData()
                                                except Exception as e:
                                                    clipdata = None
                                                    last_error = e
                                                win32clipboard.CloseClipboard()
                                                if clipdata == content:
                                                    print(f"[剪贴板] 高频快捷键(win32clipboard)复制成功: {fname}")
                                                    success = True
                                                    break
                                            except Exception as werr:
                                                print(f"[剪贴板] win32clipboard失败: {werr}")
                                                last_error = werr
                                        if success:
                                            return
                                        else:
                                            # 多次失败，弹窗提示
                                            messagebox.showwarning("剪贴板被占用", "检测到截图工具正在占用剪贴板，无法写入文本。请关闭截图工具或等待其释放后再试。", parent=root)
                                            print(f"[剪贴板] 高频快捷键(win32clipboard)多次写入失败: {last_error}")
                                            return
                                    # 兜底用tkinter
                                    try:
                                        root.clipboard_clear()
                                        root.clipboard_append(content)
                                        root.update()
                                        print(f"[剪贴板] 高频快捷键(tkinter)复制成功: {fname}")
                                    except Exception:
                                        try:
                                            pyperclip.copy(content)
                                            print(f"[剪贴板] 高频快捷键(pyperclip)复制成功: {fname}")
                                        except Exception as pcerr:
                                            print(f"[剪贴板] 高频快捷键复制失败: {fname}, {str(pcerr)}")
                            except Exception as e:
                                print(f"[高频快捷键] 读取prompt内容失败: {fname}, {str(e)}")
                        return callback
                    hotkey_manager.register_hotkey(hotkey, create_callback(filename))
                    print(f"[高频快捷键自动注册] 成功注册: {filename} -> {hotkey}")
            except Exception as e:
                print(f"[高频快捷键自动注册] 加载失败: {str(e)}")
        
        # 创建事件循环
        loop = asyncio.get_event_loop()
        
        def update():
            try:
                loop.run_until_complete(asyncio.sleep(0))
                root.after(100, update)  # 每100ms更新一次事件循环
            except Exception as e:
                logging.error(f"事件循环更新错误: {str(e)}")
                
        update()  # 启动事件循环更新
        root.mainloop()
        
    except Exception as e:
        # 记录错误到日志
        logging.error(f"程序运行错误: {str(e)}")
        logging.error(traceback.format_exc())
        
        # 显示错误消息框
        messagebox.showerror("错误", 
                           f"程序运行出错:\n{str(e)}\n\n详细错误信息已保存到logs目录")
        sys.exit(1)

if __name__ == "__main__":
    asyncio.run(async_main()) 